#include <amxmodx>
#include <amxmisc>
#include <fakemeta>

#define PLUGIN "Advanced HUD/DHUD Manager"
#define VERSION "1.5"
#define AUTHOR "PluginHUB"

#define ADMIN_FLAG ADMIN_RCON // Флаг "l"

enum _:DataTypes { Type_None, Type_DHUD, Type_HUD };

// Структура для редактируемого сообщения
new g_EditorType[33];
new g_EditorTitle[33][32];
new g_EditorText[33][128];
new Float:g_EditorX[33] = { 0.51, ... };
new Float:g_EditorY[33] = { 0.35, ... };
new g_EditorColorIdx[33];
new g_EditorEffectIdx[33];
new g_EditorTarget[33];     // 0 - всем, 1 - админам
new g_EditorAliveOnly[33];  // 0 - всем, 1 - только живым
new g_EditorMode[33];       // 0 - разово, 1 - постоянно

// Ожидание ввода текста (1 - название, 2 - текст)
new g_Step[33];

// Структура для загруженных/активных сообщений на сервере
#define MAX_ACTIVE_MESSAGES 32
new act_Type[MAX_ACTIVE_MESSAGES];
new act_Title[MAX_ACTIVE_MESSAGES][32];
new act_Text[MAX_ACTIVE_MESSAGES][128];
new Float:act_X[MAX_ACTIVE_MESSAGES];
new Float:act_Y[MAX_ACTIVE_MESSAGES];
new act_ColorIdx[MAX_ACTIVE_MESSAGES];
new act_EffectIdx[MAX_ACTIVE_MESSAGES];
new act_Target[MAX_ACTIVE_MESSAGES];
new act_AliveOnly[MAX_ACTIVE_MESSAGES];
new act_Mode[MAX_ACTIVE_MESSAGES];
new act_Count = 0;

// Цвета
new const ColorNames[10][] = {
    "Белый", "Красный", "Зеленый", "Синий", "Желтый", 
    "Голубой", "Розовый", "Оранжевый", "Фиолетовый", "Серый"
};

new const g_Colors[10][3] = {
    {255, 255, 255},
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255},
    {255, 255, 0},
    {0, 255, 255},
    {255, 0, 255},
    {255, 128, 0},
    {128, 0, 128},
    {192, 192, 192}
};

// Реальные поддерживаемые эффекты движка HUD (0 - обычный, 2 - печать)
new const EffectNames[2][] = {
    "Обычный", "Печать текста (эффект пишущей машинки)"
};
new const g_EffectValues[2] = { 0, 2 };

public plugin_init() {
    register_plugin(PLUGIN, VERSION, AUTHOR);
    
    register_clcmd("say /dhud", "CmdMain");
    register_clcmd("say_team /dhud", "CmdMain");
    
    register_clcmd("hud_input_title", "ClCmdInputTitle");
    register_clcmd("hud_input_text", "ClCmdInputText");
    
    LoadMessagesFromFile();
    set_task(1.0, "Task_ShowHudMessages", _, _, _, "b");
}

public client_disconnected(id) {
    ResetData(id);
}

ResetData(id) {
    g_EditorType[id] = Type_None;
    g_EditorTitle[id][0] = '^0';
    g_EditorText[id][0] = '^0';
    g_EditorX[id] = 0.51;
    g_EditorY[id] = 0.35;
    g_EditorColorIdx[id] = 0;
    g_EditorEffectIdx[id] = 0;
    g_EditorTarget[id] = 0;
    g_EditorAliveOnly[id] = 0;
    g_EditorMode[id] = 0;
    g_Step[id] = 0;
}

// Главное меню
public CmdMain(id) {
    if (!(get_user_flags(id) & ADMIN_FLAG)) {
        client_print(id, print_chat, "[HUD] У вас нет доступа к этой команде.");
        return PLUGIN_HANDLED;
    }
    
    new menu = menu_create("\y[HUD/DHUD Manager] Главное меню", "HandlerMain");
    
    menu_additem(menu, "DHUD - Информация", "1");
    menu_additem(menu, "HUD - Информация", "2");
    menu_additem(menu, "Сохранённые", "3");
    
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
    return PLUGIN_HANDLED;
}

public HandlerMain(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        return PLUGIN_HANDLED;
    }
    
    new data[6], dummy;
    menu_item_getinfo(menu, item, dummy, data, charsmax(data), _, _, dummy);
    menu_destroy(menu);
    
    new choice = str_to_num(data);
    switch (choice) {
        case 1, 2: {
            ResetData(id);
            g_EditorType[id] = (choice == 1) ? Type_DHUD : Type_HUD;
            SubMenuCreate(id);
        }
        case 3: {
            ShowSavedList(id);
        }
    }
    return PLUGIN_HANDLED;
}

// Подменю создания
public SubMenuCreate(id) {
    new title[64];
    formatex(title, charsmax(title), "\yСоздание %s-сообщения^n\w[1]. Введите название", g_EditorType[id] == Type_DHUD ? "DHUD" : "HUD");
    
    new menu = menu_create(title, "HandlerSubMenuCreate");
    menu_additem(menu, "Ввести название", "1");
    
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
}

public HandlerSubMenuCreate(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        CmdMain(id);
        return PLUGIN_HANDLED;
    }
    menu_destroy(menu);
    
    g_Step[id] = 1;
    client_print(id, print_chat, "[HUD] Введите название для сохранения в чате");
    client_cmd(id, "messagemode hud_input_title");
    return PLUGIN_HANDLED;
}

public ClCmdInputTitle(id) {
    if (!(get_user_flags(id) & ADMIN_FLAG) || g_Step[id] != 1) return PLUGIN_HANDLED;
    
    new arg[32];
    read_args(arg, charsmax(arg));
    remove_quotes(arg);
    trim(arg);
    
    if (arg[0] == 0) {
        client_print(id, print_chat, "[HUD] Название не может быть пустым!");
        SubMenuCreate(id);
        return PLUGIN_HANDLED;
    }
    
    copy(g_EditorTitle[id], charsmax(g_EditorTitle[]), arg);
    g_Step[id] = 2;
    
    client_print(id, print_chat, "[HUD] Введите текст информации через messagemode.");
    client_cmd(id, "messagemode hud_input_text");
    return PLUGIN_HANDLED;
}

public ClCmdInputText(id) {
    if (!(get_user_flags(id) & ADMIN_FLAG) || g_Step[id] != 2) return PLUGIN_HANDLED;
    
    new arg[128];
    read_args(arg, charsmax(arg));
    remove_quotes(arg);
    trim(arg);
    
    if (arg[0] == 0) {
        client_print(id, print_chat, "[HUD] Текст не может быть пустым!");
        SubMenuCreate(id);
        return PLUGIN_HANDLED;
    }
    
    copy(g_EditorText[id], charsmax(g_EditorText[]), arg);
    g_Step[id] = 0;
    
    ShowEditorMenu(id);
    return PLUGIN_HANDLED;
}

// Меню редактора
public ShowEditorMenu(id) {
    new title[128];
    formatex(title, charsmax(title), "\yРедактор %s^n\rНазвание:\w %s", g_EditorType[id] == Type_DHUD ? "DHUD" : "HUD", g_EditorTitle[id]);
    
    new menu = menu_create(title, "HandlerEditorMenu");
    
    menu_additem(menu, "Перемещение", "1");
    
    new colorStr[64];
    formatex(colorStr, charsmax(colorStr), "Изменить цвет: \y[%s]", ColorNames[g_EditorColorIdx[id]]);
    menu_additem(menu, colorStr, "2");
    
    new effStr[64];
    formatex(effStr, charsmax(effStr), "Изменить эффект: \y[%s]", EffectNames[g_EditorEffectIdx[id]]);
    menu_additem(menu, effStr, "3");
    
    new targetStr[64];
    formatex(targetStr, charsmax(targetStr), "Кому виден: \y[%s]", g_EditorTarget[id] == 0 ? "Всем" : "Админам");
    menu_additem(menu, targetStr, "4");
    
    new aliveStr[64];
    formatex(aliveStr, charsmax(aliveStr), "Только живым: \y[%s]", g_EditorAliveOnly[id] == 0 ? "Выкл" : "Вкл");
    menu_additem(menu, aliveStr, "5");
    
    new modeStr[64];
    formatex(modeStr, charsmax(modeStr), "Режим показа: \y[%s]", g_EditorMode[id] == 0 ? "Разово" : "Постоянно");
    menu_additem(menu, modeStr, "6");
    
    menu_additem(menu, "\r[Удалить запись]", "7");
    menu_addblank(menu, 0);
    menu_additem(menu, "\y[Сохранить]", "8");
    
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
    
    PreviewMessage(id);
}

public HandlerEditorMenu(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        CmdMain(id);
        return PLUGIN_HANDLED;
    }
    
    new data[6], dummy;
    menu_item_getinfo(menu, item, dummy, data, charsmax(data), _, _, dummy);
    menu_destroy(menu);
    
    new choice = str_to_num(data);
    switch (choice) {
        case 1: ShowMoveMenu(id);
        case 2: ShowColorMenu(id);
        case 3: ShowEffectMenu(id);
        case 4: {
            g_EditorTarget[id] = g_EditorTarget[id] == 0 ? 1 : 0;
            ShowEditorMenu(id);
        }
        case 5: {
            g_EditorAliveOnly[id] = g_EditorAliveOnly[id] == 0 ? 1 : 0;
            ShowEditorMenu(id);
        }
        case 6: {
            g_EditorMode[id] = g_EditorMode[id] == 0 ? 1 : 0;
            ShowEditorMenu(id);
        }
        case 7: {
            DeleteMessageByName(g_EditorTitle[id]);
            client_print(id, print_chat, "[HUD] Запись удалена!");
            CmdMain(id);
        }
        case 8: {
            SaveMessage(id);
            LoadMessagesFromFile();
            client_print(id, print_chat, "[HUD] Успешно сохранено и запущено!");
            CmdMain(id);
        }
    }
    return PLUGIN_HANDLED;
}

// Меню перемещения
public ShowMoveMenu(id) {
    new menu = menu_create("\yПеремещение HUD/DHUD (шаг 5 юнитов)", "HandlerMoveMenu");
    
    menu_additem(menu, "Перемещение вверх на 5", "1");
    menu_additem(menu, "Перемещение вниз на 5", "2");
    menu_additem(menu, "Перемещение влево на 5", "3");
    menu_additem(menu, "Перемещение вправо на 5", "4");
    
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
}

public HandlerMoveMenu(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        ShowEditorMenu(id);
        return PLUGIN_HANDLED;
    }
    
    new data[6], dummy;
    menu_item_getinfo(menu, item, dummy, data, charsmax(data), _, _, dummy);
    menu_destroy(menu);
    
    new choice = str_to_num(data);
    switch (choice) {
        case 1: g_EditorY[id] -= 0.05;
        case 2: g_EditorY[id] += 0.05;
        case 3: g_EditorX[id] -= 0.05;
        case 4: g_EditorX[id] += 0.05;
    }
    
    if (g_EditorX[id] < 0.0) g_EditorX[id] = 0.0;
    if (g_EditorX[id] > 1.0) g_EditorX[id] = 1.0;
    if (g_EditorY[id] < 0.0) g_EditorY[id] = 0.0;
    if (g_EditorY[id] > 1.0) g_EditorY[id] = 1.0;
    
    ShowMoveMenu(id);
    return PLUGIN_HANDLED;
}

// Меню цвета
public ShowColorMenu(id) {
    new menu = menu_create("\yВыберите цвет текста", "HandlerColorMenu");
    new name[64];
    for (new i = 0; i < 10; i++) {
        formatex(name, charsmax(name), "%s", ColorNames[i]);
        menu_additem(menu, name, fmt("%d", i));
    }
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
}

public HandlerColorMenu(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        ShowEditorMenu(id);
        return PLUGIN_HANDLED;
    }
    new data[6], dummy;
    menu_item_getinfo(menu, item, dummy, data, charsmax(data), _, _, dummy);
    menu_destroy(menu);
    g_EditorColorIdx[id] = str_to_num(data);
    ShowEditorMenu(id);
    return PLUGIN_HANDLED;
}

// Меню эффекта
public ShowEffectMenu(id) {
    new menu = menu_create("\yВыберите эффект", "HandlerEffectMenu");
    new name[64];
    for (new i = 0; i < 2; i++) {
        formatex(name, charsmax(name), "%s", EffectNames[i]);
        menu_additem(menu, name, fmt("%d", i));
    }
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
}

public HandlerEffectMenu(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        ShowEditorMenu(id);
        return PLUGIN_HANDLED;
    }
    new data[6], dummy;
    menu_item_getinfo(menu, item, dummy, data, charsmax(data), _, _, dummy);
    menu_destroy(menu);
    g_EditorEffectIdx[id] = str_to_num(data);
    ShowEditorMenu(id);
    return PLUGIN_HANDLED;
}

// Предпросмотр создателю
PreviewMessage(id) {
    new cIdx = g_EditorColorIdx[id];
    new effVal = g_EffectValues[g_EditorEffectIdx[id]];
    
    if (g_EditorType[id] == Type_DHUD) {
        set_dhudmessage(g_Colors[cIdx][0], g_Colors[cIdx][1], g_Colors[cIdx][2], g_EditorX[id], g_EditorY[id], effVal, 0.0, 1.5, 0.1, 0.2);
        show_dhudmessage(id, "%s", g_EditorText[id]);
    } else {
        set_hudmessage(g_Colors[cIdx][0], g_Colors[cIdx][1], g_Colors[cIdx][2], g_EditorX[id], g_EditorY[id], effVal, 0.0, 1.5, 0.1, 0.2);
        show_hudmessage(id, "%s", g_EditorText[id]);
    }
}

// Глобальный таск вывода сообщений на экран игроков
public Task_ShowHudMessages() {
    if (act_Count <= 0) return;
    
    new players[32], pnum, pid;
    get_players(players, pnum, "h");
    
    for (new i = 0; i < pnum; i++) {
        pid = players[i];
        new is_admin = (get_user_flags(pid) & ADMIN_FLAG);
        new is_alive = is_user_alive(pid);
        
        for (new m = 0; m < act_Count; m++) {
            if (act_Target[m] == 1 && !is_admin) continue;
            if (act_AliveOnly[m] == 1 && !is_alive) continue;
            
            new cIdx = act_ColorIdx[m];
            new effVal = g_EffectValues[act_EffectIdx[m]];
            
            if (act_Type[m] == Type_DHUD) {
                set_dhudmessage(g_Colors[cIdx][0], g_Colors[cIdx][1], g_Colors[cIdx][2], act_X[m], act_Y[m], effVal, 0.0, 1.1, 0.1, 0.2);
                show_dhudmessage(pid, "%s", act_Text[m]);
            } else {
                set_hudmessage(g_Colors[cIdx][0], g_Colors[cIdx][1], g_Colors[cIdx][2], act_X[m], act_Y[m], effVal, 0.0, 1.1, 0.1, 0.2);
                show_hudmessage(pid, "%s", act_Text[m]);
            }
        }
    }
}

// Сохранение в файл
SaveMessage(id) {
    new dir[128];
    get_configsdir(dir, charsmax(dir));
    formatex(dir, charsmax(dir), "%s/hud_manager", dir);
    if (!dir_exists(dir)) mkdir(dir);
    
    new filepath[256];
    formatex(filepath, charsmax(filepath), "%s/saved_messages.ini", dir);
    
    DeleteMessageByName(g_EditorTitle[id]);
    
    new file = fopen(filepath, "a+");
    if (file) {
        fprintf(file, "^"%s^" ^"%s^" ^"%s^" %f %f %d %d %d %d %d^n",
            g_EditorType[id] == Type_DHUD ? "DHUD" : "HUD",
            g_EditorTitle[id],
            g_EditorText[id],
            g_EditorX[id],
            g_EditorY[id],
            g_EditorColorIdx[id],
            g_EditorEffectIdx[id],
            g_EditorTarget[id],
            g_EditorAliveOnly[id],
            g_EditorMode[id]
        );
        fclose(file);
    }
}

// Загрузка сообщений из файла
LoadMessagesFromFile() {
    act_Count = 0;
    new dir[128];
    get_configsdir(dir, charsmax(dir));
    new filepath[256];
    formatex(filepath, charsmax(filepath), "%s/hud_manager/saved_messages.ini", dir);
    
    if (!file_exists(filepath)) return;
    
    new file = fopen(filepath, "r");
    new buffer[512], type[8], title[32], text[128], sX[16], sY[16], sColor[8], sEff[8], sTarget[8], sAlive[8], sMode[8];
    
    while (!feof(file) && act_Count < MAX_ACTIVE_MESSAGES) {
        fgets(file, buffer, charsmax(buffer));
        trim(buffer);
        if (!buffer[0]) continue;
        
        parse(buffer, type, charsmax(type), title, charsmax(title), text, charsmax(text), sX, charsmax(sX), sY, charsmax(sY), sColor, charsmax(sColor), sEff, charsmax(sEff), sTarget, charsmax(sTarget), sAlive, charsmax(sAlive), sMode, charsmax(sMode));
        
        if (str_to_num(sMode) == 1) {
            act_Type[act_Count] = equali(type, "DHUD") ? Type_DHUD : Type_HUD;
            copy(act_Title[act_Count], charsmax(act_Title[]), title);
            copy(act_Text[act_Count], charsmax(act_Text[]), text);
            act_X[act_Count] = str_to_float(sX);
            act_Y[act_Count] = str_to_float(sY);
            act_ColorIdx[act_Count] = str_to_num(sColor);
            act_EffectIdx[act_Count] = str_to_num(sEff);
            act_Target[act_Count] = str_to_num(sTarget);
            act_AliveOnly[act_Count] = str_to_num(sAlive);
            act_Mode[act_Count] = 1;
            act_Count++;
        }
    }
    fclose(file);
}

// Удаление записи
DeleteMessageByName(const targetTitle[]) {
    new dir[128];
    get_configsdir(dir, charsmax(dir));
    new filepath[256], tempPath[256];
    formatex(filepath, charsmax(filepath), "%s/hud_manager/saved_messages.ini", dir);
    formatex(tempPath, charsmax(tempPath), "%s/hud_manager/saved_messages.tmp", dir);
    
    if (!file_exists(filepath)) return;
    
    new file = fopen(filepath, "r");
    new temp = fopen(tempPath, "w");
    new buffer[512], type[8], title[32];
    
    while (!feof(file)) {
        fgets(file, buffer, charsmax(buffer));
        trim(buffer);
        if (!buffer[0]) continue;
        
        parse(buffer, type, charsmax(type), title, charsmax(title));
        if (!equali(title, targetTitle)) {
            fputs(temp, fmt("%s^n", buffer));
        }
    }
    fclose(file);
    fclose(temp);
    
    delete_file(filepath);
    rename_file(tempPath, filepath, 1);
    LoadMessagesFromFile();
}

// Список сохраненных
ShowSavedList(id) {
    new dir[128];
    get_configsdir(dir, charsmax(dir));
    new filepath[256];
    formatex(filepath, charsmax(filepath), "%s/hud_manager/saved_messages.ini", dir);
    
    if (!file_exists(filepath)) {
        client_print(id, print_chat, "[HUD] Нет сохраненных записей.");
        CmdMain(id);
        return;
    }
    
    new menu = menu_create("\yСохранённые настройки", "HandlerSavedList");
    new file = fopen(filepath, "r");
    new buffer[512], type[8], title[32];
    
    while (!feof(file)) {
        fgets(file, buffer, charsmax(buffer));
        trim(buffer);
        if (!buffer[0]) continue;
        
        parse(buffer, type, charsmax(type), title, charsmax(title));
        menu_additem(menu, fmt("[%s] %s", type, title), buffer);
    }
    fclose(file);
    
    menu_setprop(menu, MPROP_EXIT, MEXIT_ALL);
    menu_display(id, menu, 0);
}

public HandlerSavedList(id, menu, item) {
    if (item == MENU_EXIT) {
        menu_destroy(menu);
        CmdMain(id);
        return PLUGIN_HANDLED;
    }
    
    new buffer[512], dummy;
    menu_item_getinfo(menu, item, dummy, buffer, charsmax(buffer), _, _, dummy);
    menu_destroy(menu);
    
    new type[8], title[32], text[128], sX[16], sY[16], sColor[8], sEff[8], sTarget[8], sAlive[8], sMode[8];
    parse(buffer, type, charsmax(type), title, charsmax(title), text, charsmax(text), sX, charsmax(sX), sY, charsmax(sY), sColor, charsmax(sColor), sEff, charsmax(sEff), sTarget, charsmax(sTarget), sAlive, charsmax(sAlive), sMode, charsmax(sMode));
    
    g_EditorType[id] = equali(type, "DHUD") ? Type_DHUD : Type_HUD;
    copy(g_EditorTitle[id], charsmax(g_EditorTitle[]), title);
    copy(g_EditorText[id], charsmax(g_EditorText[]), text);
    g_EditorX[id] = str_to_float(sX);
    g_EditorY[id] = str_to_float(sY);
    g_EditorColorIdx[id] = str_to_num(sColor);
    g_EditorEffectIdx[id] = str_to_num(sEff);
    g_EditorTarget[id] = str_to_num(sTarget);
    g_EditorAliveOnly[id] = str_to_num(sAlive);
    g_EditorMode[id] = str_to_num(sMode);
    
    ShowEditorMenu(id);
    return PLUGIN_HANDLED;
}